package com.iap.admin.mediator
{
	import com.iap.client.event.FillerEvent;
	import com.iap.common.signal.FillerRequestSignal;
	import com.iap.admin.view.FillerView;
	import com.iap.admin.view.filler.FillerEditView;
	import com.iap.admin.view.filler.code.FillerEditViewCode;
	import com.iap.app.AppGlobal;
	import com.iap.app.StatusCode;
	import com.iap.app.model.ServiceResponse;
	import com.iap.common.model.Filler;
	import com.iap.common.model.Image;
	
	import spark.components.Group;
	import spark.primitives.supportClasses.FilledElement;
	import com.iap.common.mediator.BaseMediator;

	public class FillerEditMediator extends BaseMediator
	{
		[Inject]
		public var view:FillerEditView;
		[Inject]
		public var request:FillerRequestSignal;
		
		override public function onRegister():void
		{
			view.onCancel.add(onCancel);
			view.onSubmit.add(onSubmit);
			view.imageControl.onImageAdded.add(imageAddedHandler);
			addContextListener(FillerEvent.RESPONSE, responseHandler);
		}
		
		private function onCancel(itemName:String):void
		{
			switch(itemName)
			{
				case FillerEditViewCode.CANCEL_NAME:
				{
					optionBack();
					break;
				}
			}
		}
		
		private function optionBack():void
		{
			setView(view.parent as Group, new FillerView(), FX_GLIDE_OUT);
		}
		
		private function onSubmit(model:Filler, task:String):void
		{
			AppGlobal.startWait();
			request.dispatch(model, task);
		}
		
		private function responseHandler(evt:FillerEvent):void
		{
			AppGlobal.endWait();
			var response:ServiceResponse = evt.response;
			if(response.task == FillerRequestSignal.SAVE)
			{
				var image:Image = (response.result as Filler).image;
				view.imageControl.setImage(image);
				if(!view.canCloseForm)
					return;
			}
			if(response.status.code == StatusCode.OK || view.canCloseForm)
				optionBack();
		}
		
		private function imageAddedHandler(item:Image):void
		{
			view.setImage(item);
		}
	}
}